package red.yancloud.www.ui.activity

import android.content.Intent
import android.util.Log
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_red_travel.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import red.yancloud.www.common.Constants
import red.yancloud.www.util.ToastUtils
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.*
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.Glide
import com.bumptech.glide.request.transition.Transition
import kotlinx.android.synthetic.main.activity_red_travel.smartRefreshLayout
import red.yancloud.www.R
import red.yancloud.www.base.BaseRefreshActivity
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.RedTravel
import red.yancloud.www.internet.bean.TypeData
import red.yancloud.www.ui.adapter.*
import red.yancloud.www.util.AppUtils
import kotlin.math.abs


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/13 20:09
 * E_Mail：yh131412hys@163.com
 * Describe：红色文旅
 * Change：
 * @Version：V1.0
 */
class RedTravelActivity : BaseRefreshActivity(), View.OnClickListener {

    private val TAG = "redTravelActiv"

    private var typeSelectPosition = -1//用于记录用户选择的变量
    private var childTypeSelectPosition = -1//用于记录用户选择的变量

    private var keyword:String=""
    private var id:String=""
    private var pid:String=""
    private var typeData:TypeData?=null
    private lateinit var typeList:ArrayList<TypeData>
    private lateinit var mTypeAdapter:TypeRecyclerAdapter
    private lateinit var mAdapter: RedTravelRecyclerAdapter

    private lateinit var arrayList:ArrayList<redTravelBean>

    override val layoutId: Int
        get() = R.layout.activity_red_travel

    override fun initData() {
        super.initData()

//        Observable.create(object :ObservableOnSubscribe<List<TypeData>>{
//            override fun subscribe(emitter: ObservableEmitter<List<TypeData>>) {
//                /** http://www.yancloud.red/Memorial/Index/index/tid/3053/p/1.html
//                 * 0:全部时期
//                3051:土地革命时期
//                3052:抗日战争
//                3053:长征路上
//                3054:解放战争
//                3055:社会主义建设
//                3056:朝鲜战争
//                3057:越南战争
//                3058:重要会议
//                 */
//                //			http://www.yancloud.red/Memorial/Index/index/p/3.html
//                val doc: Document = Jsoup.connect("http://www.yancloud.red/Memorial/Index/index/p/1.html").get()
//                //			纪念馆分类
//                val memorialTypeSelects = doc.select("div[class=main-cont-left fl mr30] > ul > li")
//                for (element in memorialTypeSelects) {
//
//                    typeList.add(TypeData(element.select("p")[0].text(),""))
//                }
//                emitter.onNext(typeList)
//            }
//        }).subscribeOn(Schedulers.io())
//            .subscribeOn(Schedulers.newThread())
//            .observeOn(AndroidSchedulers.mainThread())
//            .subscribe(object :Observer<List<TypeData>>{
//                override fun onComplete() {
//                }
//
//                override fun onSubscribe(d: Disposable) {
//                }
//
//                override fun onNext(t: List<TypeData>) {
//
//                    Log.d(TAG,t.toString())
//                    mTypeAdapter.addData(t)
//                }
//
//                override fun onError(e: Throwable) {
//                }
//            })

        typeList= ArrayList()

//        RedCloudApis.getInstance().travelType(object : Observer<redTravelType> {
//            override fun onComplete() {
//            }
//
//            override fun onSubscribe(d: Disposable) {
//            }
//
//            override fun onNext(t: redTravelType) {
//
//                if (t.code == Constants.SYSTEM_OK&&t.data!=null&&t.data.area!=null) {
//
//                    for (i in 0 until t.data.area.size) {
//
//                        typeList.add(TypeData(t.data.area[i],i.toString()))
//                    }
//                    mTypeAdapter.addData(typeList)
//                }
//            }
//
//            override fun onError(e: Throwable) {
//            }
//        })

//        Observable.create(object :ObservableOnSubscribe<List<redTravelBean>>{
//            override fun subscribe(emitter: ObservableEmitter<List<redTravelBean>>) {
//                /** http://www.yancloud.red/Memorial/Index/index/tid/3053/p/1.html
//                 * 0:全部时期
//                3051:土地革命时期
//                3052:抗日战争
//                3053:长征路上
//                3054:解放战争
//                3055:社会主义建设
//                3056:朝鲜战争
//                3057:越南战争
//                3058:重要会议
//                 */
//                arrayList = ArrayList()
//                typeList= ArrayList()
//                for (i in 1..5) {
//
//                    getInfo(i)
//                    Log.d(TAG,"$i$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
//                }
//                emitter.onNext(arrayList)
//            }
//        }).subscribeOn(Schedulers.io())
//            .subscribeOn(Schedulers.newThread())
//            .observeOn(AndroidSchedulers.mainThread())
//            .subscribe(object :Observer<List<redTravelBean>>{
//                override fun onComplete() {
//                }
//
//                override fun onSubscribe(d: Disposable) {
//                }
//
//                override fun onNext(t: List<redTravelBean>) {
//
//                    Log.d(TAG,t.toString())
//                    mAdapter.addData(t)
//                }
//
//                override fun onError(e: Throwable) {
//                }
//            })

//        arrayListAdd = ArrayList()
    }

    override fun configViews() {
        super.configViews()

        redTravelActivity_back_iv.setOnClickListener(this)
        initSearchEditText()
    }

    private fun initSearchEditText() {

//        在清单文件对应的Activity中添加如下属性，防止布局被软键盘顶上去 android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
        redTravelActivity_search_et.setOnEditorActionListener(object : TextView.OnEditorActionListener {

            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

                if (actionId== EditorInfo.IME_ACTION_SEARCH) {

                    AppUtils.closeInoutDecorView(this@RedTravelActivity)
                    keyword = redTravelActivity_search_et.text.toString().trim()
                    redTravelActivity_search_et.text!!.clear()
                    if (TextUtils.isEmpty(keyword)) {

                        ToastUtils.showToast("请输入搜索关键字")
                        return true
                    }

                    page = 1
                    id = ""
                    pid =""
                    typeSelectPosition = -1
                    redTravelActivity_chileType_rV.visibility = View.GONE
                    getRefreshDataList()
                    keyword=""
                    return true
                }
                return false
            }
        })
    }

    override fun initRecyclerView() {

//        纪念馆类别
        redTravelActivity_type_rV.layoutManager=LinearLayoutManager(mContext,RecyclerView.HORIZONTAL,false)
        mTypeAdapter = TypeRecyclerAdapter(R.layout.item_read_type_list)
        redTravelActivity_type_rV.adapter= mTypeAdapter
        mTypeAdapter.onItemClickListener = object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                //获取选中的参数
                typeSelectPosition = position
                mTypeAdapter.setSelectPosition(typeSelectPosition)

                page=1

                typeData = mTypeAdapter.data[position] as TypeData
                id= typeData!!.typeId
                pid = ""
                if (typeData!!.childrenBeanList != null) {

                    pid = id
                    id = typeData!!.childrenBeanList[0].id

                    redTravelActivity_chileType_rV.visibility = View.VISIBLE
                    redTravelActivity_chileType_rV.layoutManager=GridLayoutManager(mContext,4,RecyclerView.VERTICAL,false)
                    val mChildTypeAdapter = RedTravelTypeRecyclerAdapter(R.layout.item_repository_sort_value_list)
                    mChildTypeAdapter.addData(typeData!!.childrenBeanList)
                    redTravelActivity_chileType_rV.adapter= mChildTypeAdapter
                    mChildTypeAdapter.onItemClickListener = object :BaseQuickAdapter.OnItemClickListener{
                        override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                            childTypeSelectPosition = position
                            mChildTypeAdapter.setSelectPosition(childTypeSelectPosition)

                            id = (mChildTypeAdapter.data[position] as RedTravel.DataBean.MenusBean.ChildrensBean).id

                            getRefreshDataList()
                        }
                    }
                }else{

                    redTravelActivity_chileType_rV.visibility = View.GONE
                }

                getRefreshDataList()
            }
        }

//        纪念馆图片列表
        redTravelActivity_rV.layoutManager=StaggeredGridLayoutManager(2,RecyclerView.VERTICAL)
        val staggeredGridLayoutManager = redTravelActivity_rV.layoutManager as StaggeredGridLayoutManager
        redTravelActivity_rV.addItemDecoration(StaggeredDividerItemDecoration(mContext,10))
//        可以看出，当滑到底部的时候，最后一个item等待一段时间才显示出来。这是RecyclerView使用瀑布流布局时自带的动画效果，而这个动画效果看起来不怎么舒服，一般都会去掉。
//        调用RecyclerView的setAnimator将Animator设置为null，并调用StaggeredLayoutManager的setGapStrategy方法设置为StaggeredGridLayoutManager.GAP_HANDLING_NONE
        staggeredGridLayoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
//        redTravelActivity_rV.itemAnimator = null
        (redTravelActivity_rV.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
        (redTravelActivity_rV.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        (redTravelActivity_rV.itemAnimator as DefaultItemAnimator).changeDuration = 0
        redTravelActivity_rV.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
//                val first = IntArray(2)
//
//                (recyclerView.layoutManager as StaggeredGridLayoutManager).findFirstCompletelyVisibleItemPositions(first)
//                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1 )) {
//                    staggeredGridLayoutManager.invalidateSpanAssignments()
//                }
                staggeredGridLayoutManager.invalidateSpanAssignments();//防止第一行到顶部有空白
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                if (typeData != null && typeData!!.childrenBeanList!=null){

                    if(abs(dy) >80){

                        if (dy>0){

                            redTravelActivity_type_rV.visibility = View.GONE
                        }else if(dy<0){

                            redTravelActivity_type_rV.visibility = View.VISIBLE
                        }
                    }
                }
            }
        })
        mAdapter = RedTravelRecyclerAdapter(R.layout.item_red_travel_list)
        redTravelActivity_rV.adapter=mAdapter
        mAdapter.onItemClickListener=object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                startActivity(Intent(mContext,NewsInfoActivity::class.java)
                    .putExtra("url", "${Constants.API_BASE_RED_CLOUD_URL}News/index?id=${(mAdapter.data[position] as RedTravel.DataBean.ListBean).id}")
                    .putExtra("model",Constants.CollectModel.TRAVEL)
                    .putExtra("id",(mAdapter.data[position] as RedTravel.DataBean.ListBean).id))

            }
        }
//        如果RecyclerView中有使用上拉加载或下拉刷新的话，那么会存在两个问题。其中一个问题是进行上拉加载时，使用notifyItemDataSetChanged刷新列表，可能会出现闪动且间距错乱，解决办法是使用notifyItemRangeInserted代替刷新。
//        int start = list.size();
//        list.addAll(newItems);
//        adapter.notifyItemInserted(start, list.size());
//
//        而进行下拉刷新时，也建议用notifyItemRangeChanged代替notifyDataSetChanged
//        list.clear();
//        list.addAll(newList);
//        adapter.notifyItemRangeChanged(0, list.size());
    }

    override fun getRefreshDataList() {

        loadingDialog.show()

        RedCloudApis.getInstance()
            .getTravel(page.toString(), limit, id, pid,keyword,object : Observer<RedTravel> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: RedTravel) {

                    Log.d(TAG,t.toString())

                    if (t.code == Constants.SYSTEM_OK && t.data != null) {

                        if (t.data.menus!=null&&t.data.menus.size>0) {

                            val menuList = t.data.menus

                            typeList.clear()
                            typeList.add(TypeData("全部","",null))
                            for (i in 0 until menuList.size) {

                                typeList.add(TypeData(menuList[i].title,menuList[i].id,menuList[i].childrens))
                            }
                            mTypeAdapter.data.clear()
                            mTypeAdapter.setSelectPosition(typeSelectPosition)
                            mTypeAdapter.addData(typeList)
                            if (typeSelectPosition == -1) {

                                redTravelActivity_type_rV.scrollToPosition(0)
                            }
                        }

                        if(t.data.page!=null&& t.data.list != null && t.data.list.size > 0){

                            totalPage = t.data.page.totalPage

//                            for (memorial in t.data.memorials) {
//
//                                Glide.with(mContext).load(Constants.BASE_RED_CLOUD_HOST_URL.plus(memorial.thumbnail)).into(object : SimpleTarget<Drawable>() {
//                                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
//
//                                        val scale = resource.intrinsicWidth / resource.intrinsicHeight.toFloat()
//                                        arrayListAdd.add(redTravel.DataBean.MemorialsBean(memorial.id,memorial.title,memorial.thumbnail,scale))
//                                    }
//                                })
//                            }

                            errorView.visibility = View.GONE
                            smartRefreshLayout.visibility=View.VISIBLE

                            if (page==1) {

                                redTravelActivity_rV.scrollToPosition(0)
                                //处理数据加载后，页面刷新异常问题
                                redTravelActivity_rV.scrollBy(1,0)
                                redTravelActivity_rV.scrollBy(-1,0)
                                mAdapter.data.clear()
                                mAdapter.addData(t.data.list)
                                smartRefreshLayout.resetNoMoreData()
                                smartRefreshLayout.finishRefresh()

                                redTravelActivity_rV.scrollBy(1,0)
                                redTravelActivity_rV.scrollBy(-1,0)
                            }else {

                                mAdapter.addData(t.data.list)
                                smartRefreshLayout.finishLoadMore()
                            }
                        }else{

                            if (page==1){

                                smartRefreshLayout.finishRefresh()

                                errorView.visibility=View.VISIBLE
                                smartRefreshLayout.visibility=View.GONE
                            }else{

                                ToastUtils.showToast(getString(R.string.data_all_load))
                                smartRefreshLayout.finishLoadMoreWithNoMoreData()
                            }
                        }
                    }else{

                        if (page==1){

                            smartRefreshLayout.finishRefresh()

                            errorView.visibility=View.VISIBLE
                            smartRefreshLayout.visibility=View.GONE
                        }else{

                            ToastUtils.showToast(getString(R.string.data_all_load))
                            smartRefreshLayout.finishLoadMoreWithNoMoreData()
                        }
                    }

                    loadingDialog.dismiss()
                }

                override fun onError(e: Throwable) {

                    loadingDialog.dismiss()

                    ToastUtils.showToast(getString(R.string.current_classification_no_data))
                    errorView.visibility = View.VISIBLE
                    smartRefreshLayout.visibility=View.GONE
                }
            })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.redTravelActivity_back_iv -> finish()
            else -> {
            }
        }
    }

    class redTravelBean(var title: String?, var souce: String?, var imgurl: String?,var scale: Float,var url: String){

        override fun toString(): String {
            return "redTravelBean(title=$title, souce=$souce, imgurl=$imgurl, scale=$scale, url='$url')"
        }
    }

    private fun getInfo(id: Int) {

        //			http://www.yancloud.red/Memorial/Index/index/p/3.html
        var doc: Document = Jsoup.connect("${Constants.BASE_RED_CLOUD_HOST_URL}/Memorial/Index/index/p/$id.html").get()

        //			时期
        val timeSelects = doc.select("div[class=main-zone-right fr] > ul > li")
        for (element in timeSelects) {

//            Log.d(TAG,element.attr("data-id") + ":" + element.select("a")[0].text())
        }

//        Log.d(TAG,"---------------------------------------------------------------------------------------")

        //			纪念馆分类
        val memorialTypeSelects = doc.select("div[class=main-cont-left fl mr30] > ul > li")
        for (element in memorialTypeSelects) {

//            Log.d(TAG,element.attr("data-type") + ":" + element.select("p")[0].text())
//            typeList.add(element.select("p")[0].text())
        }

//        Log.d(TAG,"---------------------------------------------------------------------------------------")

        //			纪念馆内容
        val memorialHallSelects = doc.select("div[class=main-memorrialcont] > ul > li")
        for (select in memorialHallSelects) {

            val a = select.select("a")
            val p = select.select("a").select("p").select("em")
            val span = select.select("a").select("p").select("span")
//            Log.d(TAG,"info:" + Constants.BASE_RED_CLOUD_HOST_URL + a.attr("href") + "---imgUrl:http://www.yancloud.red" + a.select("img").attr("src") + "---title:" + p[0].text() + "---content:" + span[0].text())

            //				纪念馆详情 http://www.yancloud.red/Memorial/News/info/id/2818.html
            doc = Jsoup.connect( Constants.BASE_RED_CLOUD_HOST_URL + a.attr("href")).get()
            val infoElements = doc.select("div[class=statusitem]>ul>li")

//            for (element in infoElements) {
//
//                System.out.println(element.text())
//            }
            val imgurl = a.select("img").attr("src")

            Glide.with(mContext).load(Constants.BASE_RED_CLOUD_HOST_URL.plus(imgurl)).into(object : SimpleTarget<Drawable>() {
                override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {

                    val scale = resource.intrinsicWidth / resource.intrinsicHeight.toFloat()
                    Log.d(TAG,scale.toString())
                    arrayList.add(redTravelBean(p[0].text(),infoElements[2].text(), imgurl,scale,Constants.BASE_RED_CLOUD_HOST_URL + a.attr("href")))
                }
            })
        }
    }
}
